package com.eqdd.yiqidian.ui.discover.workdiary;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.coorchice.library.SuperTextView;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.WorkDiaryActivityCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.CompanyNewsBean;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.box.span.NoLineClickSpan;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.InputDialogActivity;
import com.eqdd.yiqidian.ui.discover.workcircle.MsgListActivity;
import com.eqdd.yiqidian.ui.discover.workcircle.WorkCircleActivity;
import com.eqdd.yiqidian.ui.discover.workcircle.WorkCircleInfoActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ClickUtil;
import com.eqdd.yiqidian.utils.CopyUtil;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.InputDialogFragment;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableResponse;
import com.shizhefei.mvc.MVCSwipeRefreshHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import io.reactivex.Flowable;
import io.rong.imkit.utils.RongDateUtils;

/**
 * 企业动态
 */
public class CompanyDynamicActivity extends BaseActivity {


    private WorkDiaryActivityCustom dataBinding;

    private ArrayList<CompanyNewsBean> workDiaryBeen = new ArrayList<>();
    private SlimAdapterEx<CompanyNewsBean> slimAdapterEx;
    private MVCSwipeRefreshHelper<List<CompanyNewsBean>> mvcHelper;
    private ModelRx2DataSource<CompanyNewsBean> dataSource;
    private InputDialogFragment inputDialogFragment;
    private int clickedPosition;

    private SlimAdapterEx<CompanyNewsBean.CommentBean> mSlimAdapterEx;
    private String talkTo;
    private SlimAdapterEx<CompanyNewsBean.CommentBean> slimTalkAdapter;
    private boolean isCommentUp;
    private int dealPos;
    private boolean isMyComment;
    private int commentId;
    private String talkContent;
    private int type;
    private MaterialDialog moreDialog;
    private int diaryId;
    private int parentId = 0;
    private String parentUserGuid;
    private int firstCommentId;
    private LayoutInflater inflater;
    private String dataType;
    private int pageNum;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        isRxbus = true;
        isDealCode = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_work_diary_list);
        inflater = LayoutInflater.from(CompanyDynamicActivity.this);
        initTopTitleBar(View.VISIBLE, "企业动态");
        dataBinding.rlHeadRoot.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.INPUT:
                    String content = data.getStringExtra(Config.CONTENT);
                    commentWorkDiary(diaryId, parentId, content, parentUserGuid, firstCommentId, (commentBean) -> {
                        if (slimTalkAdapter == null) {
                            mSlimAdapterEx.getData().add(0, (CompanyNewsBean.CommentBean) commentBean);
                            mSlimAdapterEx.notifyItemInserted(0);
                        } else if (isCommentUp) {
                            slimTalkAdapter.getData().add(0, (CompanyNewsBean.CommentBean) commentBean);
                            slimTalkAdapter.notifyItemInserted(0);
                        } else {
                            slimTalkAdapter.getData().add((CompanyNewsBean.CommentBean) commentBean);
                            slimTalkAdapter.notifyItemInserted(slimTalkAdapter.getData().size() - 1);
                        }
                        mvcHelper.refresh();
                    });
                    break;


            }
        } else if (resultCode == Config.CHANGE) {
            CompanyNewsBean bean = (CompanyNewsBean) data.getSerializableExtra("bean");
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.getData().add(requestCode, bean);
            slimAdapterEx.notifyItemChanged(requestCode + 1);
        } else if (resultCode == Config.DELETE) {
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.notifyItemRemoved(requestCode + 1);
        }
    }


    @SuppressWarnings("unchecked")
    @Override
    public void initData() {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.CHINA);

        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));

        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_company_dynamic, new SlimInjector<CompanyNewsBean>() {
            @Override
            public void onInject(CompanyNewsBean data, IViewInjector injector) {
                try {
                    injector
                            //头
                            .gone(R.id.iv_option)
                            .imageCircle(R.id.iv_head, data.getIphoto())
                            .text(R.id.tv_depart, data.getDepartName() + " " + data.getPostName())
                            .text(R.id.tv_time, RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), CompanyDynamicActivity.this))
                            .text(R.id.stv_name, data.getStaffName())
                            //城市
                            .text(R.id.tv_city, data.getLocation())
                            .visibility(R.id.tv_city, TextUtils.isEmpty(data.getLocation()) ? View.GONE : View.VISIBLE)
                            //内容
                            .visibility(R.id.layout_diary, "0".equals(data.getType()) ? View.VISIBLE : View.GONE)
                            .visibility(R.id.layout_task, "1".equals(data.getType()) ? View.VISIBLE : View.GONE)
                            .with(R.id.stv_support, v -> {
                                SuperTextView superTextView = (SuperTextView) v;
                                superTextView.setText(data.getZanCount() + "");
                                superTextView.setDrawable(getResources().getDrawable(data.isIsZan() ? R.mipmap.ic_heart_red : R.mipmap.ic_heart_hint));
                            })
                            .with(R.id.stv_msg, v -> {
                                SuperTextView superTextView = (SuperTextView) v;
                                superTextView.setText(data.getCommentCount() + "");
                                superTextView.setDrawable(getResources().getDrawable(R.mipmap.ic_comment));
                            })
                            .clicked(R.id.iv_head, v -> {
                                Bundle bundle = new Bundle();
                                bundle.putString(Config.GUID, data.getCreater());
                                startActivity(UserCardActivity.class, bundle);
                            })
                            .clicked(R.id.stv_msg, v -> {
                                clickedPosition = slimAdapterEx.getData().indexOf(data);
                                openInput(data);
                            })
                            .with(R.id.recyclerView, v -> {
                                initDialog(data, (RecyclerView) v);
                            })
                            .visibility(R.id.tv_more_comment, data.getCommentCount() > 3 ? View.VISIBLE : View.GONE)
                            .text(R.id.tv_more_comment, String.format(Locale.CHINA, "展开更多%d条评论", data.getCommentCount()))
                            .clicked(R.id.tv_more_comment, v -> {
                                String time = data.getCreateTime();
                                try {
                                    time = RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), CompanyDynamicActivity.this);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                Bundle bundle = new Bundle();
                                bundle.putInt(Config.ID, data.getObjectId());
                                bundle.putString(Config.TYPE, data.getType());
                                bundle.putString(Config.NAME, data.getStaffName());
                                bundle.putString(Config.PHONE, data.getIphoto());
                                bundle.putString(Config.DEPARTMENT, data.getDepartName() + " " + data.getPostName());
                                bundle.putString(Config.NOW_TIME, time);
                                startActivity(WorkDiaryCommentActivity.class, bundle);
                            });
                            /*.clicked(R.id.iv_option, v -> {
                                String img = null;
                                if (data.getNewImages() != null && data.getNewImages().size() > 0) {
                                    img = data.getNewImages().get(0);
                                }

                                LinkShareBuilder builder = new LinkShareBuilder(BaseWorkDiaryActivity.this);
                                builder.setTitle((data.getMessage() == null || data.getMessage() == "") ? "工作日志" : data.getMessage())
                                        .setId(data.getId() + "")
                                        .setText((data.getMessage() == null || data.getMessage() == "") ? "工作日志" : data.getMessage())
                                        .setUrl(ShareUtil.getWorkCircleUrl(data.getId() + "", ""))
                                        .setImageUrl(img)
                                        .setSource("工作日志")
                                        .setSourceOwner(data.getCreater())
                                        .build();
                                new JShareDialog(builder, BaseWorkDiaryActivity.this).show();
                            });*/
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if ("0".equals(data.getType())) {
                    injector.text(R.id.tv_diary_status, data.getMessage())
                            .text(R.id.tv_diary_filling, data.getContent());
                } else if ("1".equals(data.getType())) {
                    injector.text(R.id.tv_task_status, String.format(Locale.CHINA, "%s【%s】", data.getMessage(), data.getTitle()));
                    injector.text(R.id.tv_task_content, data.getContent());
                    float density = getResources().getDisplayMetrics().density;
                    int maxSize = getResources().getDisplayMetrics().widthPixels - (int) (density * 20);
                    if (data.getImageUrls() != null && data.getImageUrls().size() > 0) {
                        List<String> imgUrl = data.getImageUrls();
                        if (data.getImageUrls().size() == 1) {//一张图片最大边按屏幕3/4算
                            Glide.with(CompanyDynamicActivity.this)
                                    .asBitmap()
                                    .load(imgUrl.get(0))
                                    .into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                            LinearLayout.LayoutParams params;
                                            if (resource.getHeight() > resource.getWidth()) {
                                                int height = maxSize * 3 / 4;
                                                double scale = (double) resource.getWidth() / (double) resource.getHeight();
                                                int wight = (int) (height * scale);
                                                params = new LinearLayout.LayoutParams(wight, height);
                                            } else {
                                                int width = maxSize * 3 / 4;
                                                double scale = (double) resource.getHeight() / (double) resource.getWidth();
                                                int height = (int) (width * scale);
                                                params = new LinearLayout.LayoutParams(width, height);

                                            }
                                            injector.with(R.id.iv_task_1, v -> {
                                                ImageView imageView = (ImageView) v;
                                                imageView.setLayoutParams(params);
                                                ImageUtil.setImage(imgUrl.get(0), imageView);
                                            });
                                        }
                                    });
                        } else if (data.getImageUrls().size() == 2) {
                            int size = maxSize * 3 / 8;
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
                            params.setMarginEnd((int) (8 * density));
                            injector.with(R.id.iv_task_1, v -> {
                                ImageView imageView = (ImageView) v;
                                imageView.setLayoutParams(params);
                                ImageUtil.setImage(imgUrl.get(0), imageView);
                            });
                            injector.with(R.id.iv_task_2, v -> {
                                ImageView imageView = (ImageView) v;
                                imageView.setLayoutParams(params);
                                ImageUtil.setImage(imgUrl.get(1), imageView);
                            });
                        } else if (data.getImageUrls().size() >= 3) {
                            int size = (maxSize - (int) (36 * density)) / 3;
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
                            params.setMarginEnd((int) (8 * density));
                            injector.with(R.id.iv_task_1, v -> {
                                ImageView imageView = (ImageView) v;
                                imageView.setLayoutParams(params);
                                ImageUtil.setImage(imgUrl.get(0), imageView);
                            });
                            injector.with(R.id.iv_task_2, v -> {
                                ImageView imageView = (ImageView) v;
                                imageView.setLayoutParams(params);
                                ImageUtil.setImage(imgUrl.get(1), imageView);
                            });
                            injector.with(R.id.iv_task_3, v -> {
                                ImageView imageView = (ImageView) v;
                                imageView.setLayoutParams(params);
                                ImageUtil.setImage(imgUrl.get(2), imageView);
                            });
                        }
                    }
                }
                if (!data.isIsZan()) {
                    injector.enable(R.id.stv_support);
                    injector.clicked(R.id.stv_support, v -> {
                        CommitZan(data);
                        SuperTextView superTextView = ((SuperTextView) v);
                        superTextView.setText((data.getZanCount() + 1) + "");
                        superTextView.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_red));
                        data.setZanCount(data.getZanCount() + 1);
                        data.setIsZan(true);
                        injector.disable(R.id.stv_support);
                        data.getUserZan().add(0, new CompanyNewsBean.UserZanBean(user.getGuid(), user.getIphoto()));
                        ((SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter()).updateData(data.getUserZan().subList(0, data.getUserZan().size() > 3 ? 3 : data.getUserZan().size()));
                    });
                } else {
                    injector.disable(R.id.stv_support);
                }
                if (((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter() == null) {
                    ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).setLayoutManager(new LinearLayoutManager(CompanyDynamicActivity.this, LinearLayoutManager.HORIZONTAL, false));
                    SlimAdapterEx slimAdapterExHead = SlimAdapterEx.create().register(R.layout.list_item_head_img, new SlimInjector<CompanyNewsBean.UserZanBean>() {
                        @Override
                        public void onInject(CompanyNewsBean.UserZanBean data, IViewInjector injector) {
                            injector.with(R.id.iv_head_img, v -> ImageUtil.setCircleImage(data.getHeadImage(), (ImageView) v));
                        }
                    }).attachTo((RecyclerView) injector.findViewById(R.id.recyclerViewHead));
                }
                ItemClickSupport.addTo((RecyclerView) injector.findViewById(R.id.recyclerViewHead))
                        .setOnItemClickListener((recyclerView, position, v) -> {
                            Bundle bundle = new Bundle();
                            bundle.putInt(Config.ID, data.getObjectId());
                            bundle.putString(Config.TYPE, data.getType());
                            startActivity(WorkDiaryZanListActivity.class, bundle);
                        });
                injector.clicked(R.id.ll_head_img, v -> {
                    Bundle bundle = new Bundle();
                    bundle.putInt(Config.ID, data.getObjectId());
                    bundle.putString(Config.TYPE, data.getType());
                    startActivity(WorkDiaryZanListActivity.class, bundle);
                });
                ((SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter()).updateData(data.getUserZan().subList(0, data.getUserZan().size() > 3 ? 3 : data.getUserZan().size()));


            }
        }).attachTo(dataBinding.recyclerView);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    CompanyNewsBean data = slimAdapterEx.getDataItem(position);
                    String time = data.getCreateTime();
                    try {
                        time = RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), CompanyDynamicActivity.this);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt(Config.ID, data.getObjectId());
                    bundle.putString(Config.TYPE, data.getType());
                    bundle.putString(Config.NAME, data.getStaffName());
                    bundle.putString(Config.PHONE, data.getIphoto());
                    bundle.putString(Config.DEPARTMENT, data.getDepartName() + " " + data.getPostName());
                    bundle.putString(Config.NOW_TIME, time);
                    startActivity(WorkDiaryCommentActivity.class, bundle);
                });

        slimAdapterEx.updateData(workDiaryBeen);
        dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                return OkGo.<HttpResult<List<CompanyNewsBean>>>post(HttpConfig.BASE_URL + HttpConfig.COMPANY_NEWS)
                        .cacheKey(HttpConfig.BASE_URL + HttpConfig.COMPANY_NEWS + (page == 1 ? 0 : slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getId()))
                        .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                        .retryCount(1)
                        .params("companyId", user.getCompanyId())
                        .params("userGuid", user.getGuid())
                        .params("page", page == 1 ? 0 : pageNum)
                        .converter(new JsonConverter<HttpResult<List<CompanyNewsBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        })
                        .adapt(new FlowableResponse<>())
                        .doOnNext(result -> {
                            pageNum = result.body().getPage();
                        })
                        .flatMap(httpResultResponse ->
                                Flowable.just(
                                        httpResultResponse.body().getItems() == null ? new ArrayList<CompanyNewsBean>() : httpResultResponse.body().getItems()
                                )
                        );
            }
        }, 6);
        mvcHelper = new MVCSwipeRefreshHelper<>(dataBinding.swipeRefresh);
        mvcHelper.setNeedCheckNetwork(false);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }


    @Override
    public void setView() {
        initInputDialog();
        dataBinding.llRoot.removeViewAt(0);
        ClickUtil.click(dataBinding.btNewMsg, () -> {
            dataBinding.btNewMsg.setVisibility(View.GONE);
            //todo 新消息提示
            startActivity(MsgListActivity.class);
        });
    }

    private void initInputDialog() {
        inputDialogFragment = new InputDialogFragment();
        inputDialogFragment.setOnClickListener(s -> {
                    CompanyNewsBean data = slimAdapterEx.getDataItem(clickedPosition);
                    this.dataType = data.getType();
                    commentWorkDiary(data.getObjectId(), 0, s, data.getCreater(), 0, object -> {
                        inputDialogFragment.dismiss();
                        CompanyNewsBean dataItem = slimAdapterEx.getDataItem(clickedPosition);
                        dataItem.setCommentCount(dataItem.getCommentCount() + 1);
                        slimAdapterEx.notifyItemChanged(clickedPosition + 1);
                    });


//
                }
        );
    }

    @SuppressWarnings("unchecked")
    private void initDialog(CompanyNewsBean newsBean, RecyclerView recyclerView) {
        List<CompanyNewsBean.CommentBean> comment;
        if ("0".equals(newsBean.getType())) {
            comment = newsBean.getComment();
        } else if ("1".equals(newsBean.getType())) {
            comment = newsBean.getTaskComment();
        } else {
            return;
        }
        int id = newsBean.getObjectId();
        setRecyclerViewMoveFast(new LinearLayoutManager(this), recyclerView);
        mSlimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_133, new SlimInjector<CompanyNewsBean.CommentBean>() {
            @Override
            public void onInject(CompanyNewsBean.CommentBean data, IViewInjector injector) {
                List<CompanyNewsBean.CommentBean> commentResultBeen;
                if (data.getChildList() != null) {
                    commentResultBeen = data.getChildList();
                } else {
                    commentResultBeen = new ArrayList<>();
                }
                RecyclerView recyclerView = (RecyclerView) injector.findViewById(R.id.recyclerViewCommentComment);

                recyclerView.setLayoutManager(new LinearLayoutManager(CompanyDynamicActivity.this));
                SlimAdapterEx<CompanyNewsBean.CommentBean> slimAdapterExCommentChild = SlimAdapterEx.create().register(R.layout.list_item_37, new SlimInjector<CompanyNewsBean.CommentBean>() {
                    @Override
                    public void onInject(CompanyNewsBean.CommentBean data, IViewInjector injector) {
                        injector.with(R.id.tv_comment_comment, view -> {
                            TextView textView = (TextView) view;
                            SpannableString spStr = new SpannableString(data.getCreateStaffName() + ":" + " @" + data.getParentStaffName() + " " + data.getContent());
                            NoLineClickSpan firstSpan = new NoLineClickSpan("#3423ff", v -> {

                                Bundle bundle = new Bundle();
                                bundle.putString(Config.GUID, data.getCreater());
                                startActivity(UserCardActivity.class, bundle);
                            });
                            NoLineClickSpan secondSpan = new NoLineClickSpan("#3423ff", v -> {
                                Bundle bundle = new Bundle();
                                bundle.putString(Config.GUID, data.getParentUserGuid());
                                startActivity(UserCardActivity.class, bundle);
                            });
                            spStr.setSpan(firstSpan, 0, data.getCreateStaffName().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                            spStr.setSpan(secondSpan, spStr.toString().indexOf("@"), spStr.toString().indexOf("@") + 1 + data.getParentStaffName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            textView.setMovementMethod(LinkMovementMethod.getInstance());
                            textView.setText(spStr);
                        });
                    }
                }).attachTo(recyclerView).updateData(commentResultBeen);
                ItemClickSupport.addTo(recyclerView)
                        .setOnItemClickListener((recyclerView1, position, v) -> {
                            CompanyNewsBean.CommentBean dataItem = slimAdapterExCommentChild.getDataItem(position);
                            isMyComment = dataItem.getCreater().equals(AppConstent.user.getGuid());
                            commentId = dataItem.getId();
                            parentId = dataItem.getId();
                            parentUserGuid = dataItem.getCreater();
                            firstCommentId = data.getId();
                            talkTo = dataItem.getCreateStaffName();
                            talkContent = dataItem.getContent();
                            type = 2;
                            slimTalkAdapter = slimAdapterExCommentChild;
                            isCommentUp = false;
                            dealPos = position;
                            showMoreDialog(id, newsBean.getType());
                        });

                injector.text(R.id.tv_creater, data.getCreateStaffName() + ":")
                        .text(R.id.tv_comment, data.getContent())
                        .clicked(R.id.tv_comment, v -> {
                            isMyComment = data.getCreater().equals(AppConstent.user.getGuid());
                            parentId = data.getId();
                            parentUserGuid = data.getCreater();
                            firstCommentId = data.getId();
                            commentId = data.getId();
                            talkTo = data.getCreateStaffName();
                            talkContent = data.getContent();
                            type = 1;
                            slimTalkAdapter = slimAdapterExCommentChild;
                            isCommentUp = true;
                            dealPos = comment.indexOf(data);
                            mSlimAdapterEx.updateData(comment);
                            showMoreDialog(id, newsBean.getType());
                        })
                        .clicked(R.id.tv_creater, view -> {
                            Bundle bundle = new Bundle();
                            bundle.putString(Config.GUID, data.getCreater());
                            startActivity(UserCardActivity.class, bundle);
                        });

            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        mSlimAdapterEx.updateData(comment);
        //mSlimAdapterEx数据不对，总是指向 n+1
    }

    //private void openInput(String replyName, int diaryId, String dataType) {
    private void openInput(CompanyNewsBean data) {
        this.diaryId = data.getObjectId();
        parentId = 0;
        firstCommentId = 0;
        parentUserGuid = "";
        talkTo = data.getStaffName();
        slimTalkAdapter = null;
        talkTo(data.getType());

    }

    private void showMoreDialog(int id, String dataType) {
        if (moreDialog == null) {
            this.diaryId = id;
            ArrayList<Object> objects = new ArrayList<>();
            objects.add("回复");
            objects.add("复制");
            objects.add("删除");
            SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                @Override
                public void onInject(Object data, IViewInjector injector) {

                    injector.text(R.id.tv_content, (String) data);
                }
            }).updateData(objects);
            moreDialog = new MaterialDialog.Builder(this)
                    .adapter(slimAdapterEx, new LinearLayoutManager(this))
                    .build();
            moreDialog.getRecyclerView().addItemDecoration(new SectionDividerItemDecoration(this)
                    .setHeadHeight(0)
                    .setRightPadding(DensityUtil.percentW(40))
                    .setLeftPadding(DensityUtil.percentW(40))
                    .setLastBootomHeght(0));
            ItemClickSupport.addTo(moreDialog.getRecyclerView())
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        switch (position) {
                            case 0:
                                talkTo(dataType);
                                break;
                            case 1:
                                CopyUtil.copy(talkContent);
                                break;
                            case 2:
                                deleteWorkDiaryComment(commentId, dataType, type, () -> {
                                    if (isCommentUp) {
                                        mSlimAdapterEx.getData().remove(dealPos);
                                        mSlimAdapterEx.notifyItemRemoved(dealPos);
                                    } else {
                                        slimTalkAdapter.getData().remove(dealPos);
                                        slimTalkAdapter.notifyItemRemoved(dealPos);
                                    }
                                    mvcHelper.refresh();
                                });
                                break;
                        }
                        moreDialog.dismiss();
                    });
        }
        SlimAdapterEx slimAdapterExMore = (SlimAdapterEx) moreDialog.getRecyclerView().getAdapter();
        if (isMyComment && slimAdapterExMore.getData().size() == 2) {
            slimAdapterExMore.getData().add("删除");
            slimAdapterExMore.notifyItemInserted(2);
        } else if (!isMyComment && slimAdapterExMore.getData().size() == 3) {
            slimAdapterExMore.getData().remove(2);
            slimAdapterExMore.notifyItemRemoved(2);
        }
        moreDialog.show();

    }


    private void setRecyclerViewMoveFast(RecyclerView.LayoutManager layoutManager, RecyclerView recyclerView) {
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
    }

    private void talkTo(String dataType) {
        this.dataType = dataType;
        Bundle bundle = new Bundle();
        bundle.putString(Config.TALK_TO, talkTo);
        startActivityForResult(InputDialogActivity.class, bundle, Config.INPUT);
    }

    private void buttonBackGround(TextView textView, IViewInjector injector) {
        injector.background(R.id.tv_filling, R.drawable.bg_shape_click_gray);
        injector.background(R.id.tv_plan, R.drawable.bg_shape_click_gray);
        injector.background(R.id.tv_matter, R.drawable.bg_shape_click_gray);
        injector.background(R.id.tv_tomorrow_matter, R.drawable.bg_shape_click_gray);
        textView.setBackgroundResource(R.color.gray9);
    }


    public void commentWorkDiary(int articleId, int parentId, String content, String parentUserGuid, int firstCommentId, HttpUtil.ResultObjectBack resultBack) {
        String url;
        HashMap<String, String> map = new HashMap<>();
        if ("0".equals(dataType)) {
            url = HttpConfig.BASE_URL + HttpConfig.DIARY_ADD_COMMIT;
            map.put("dailyId", articleId + "");
        } else if ("1".equals(dataType)) {
            url = HttpConfig.BASE_URL + HttpConfig.TASK_ADD_COMMENT;
            map.put("taskId", articleId + "");
        } else {
            return;
        }

        OkGo.<HttpResult<CompanyNewsBean.CommentBean>>post(url)
                .params("userGuid", AppConstent.user.getGuid())
                .params(map)
                .params("parentId", parentId)
                .params("message", content)
                .params("parentUserGuid", parentUserGuid)
                .params("firstCommentId", firstCommentId)
                .execute(new DialogCallBack<HttpResult<CompanyNewsBean.CommentBean>>(CompanyDynamicActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<CompanyNewsBean.CommentBean>> response) {
                        HttpResult<CompanyNewsBean.CommentBean> httpResult = response.body();
                        // ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            resultBack.onResultBack(httpResult.getItems());
                        }
                    }
                });
    }

    public void deleteWorkDiaryComment(int commentId, String dataType, int type, HttpUtil.ResultBack resultBack) {
        String url;
        if ("0".equals(dataType)) {
            url = HttpConfig.BASE_URL + HttpConfig.DIARY_DELETE_COMMENT;
        } else if ("1".equals(dataType)) {
            url = HttpConfig.BASE_URL + HttpConfig.TASK_DELETE_COMMENT;
        } else {
            return;
        }
        OkGo.<HttpResult>post(url)
                .params("userGuid", AppConstent.user.getGuid())
                .params("commentId", commentId)
                .params("type", type)
                .execute(new DialogCallBack<HttpResult>(CompanyDynamicActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            resultBack.onResultBack();
                        }
                    }
                });
    }

    private void CommitZan(CompanyNewsBean data) {
        String url;
        HashMap<String, String> map = new HashMap<>();
        if ("0".equals(data.getType())) {
            url = HttpConfig.BASE_URL + HttpConfig.DIARY_ZAN;
            map.put("dailyId", data.getObjectId() + "");
        } else if ("1".equals(data.getType())) {
            url = HttpConfig.BASE_URL + HttpConfig.TASK_ZAN;
            map.put("taskId", data.getObjectId() + "");
        } else {
            return;
        }
        OkGo.<HttpResult>post(url)
                .params("userGuid", user.getGuid())
                .params(map)
                .execute(new JsonCallBack<HttpResult>() {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        if (httpResult.getStatus() == 200) {
                        }
                    }
                });
    }


}
